package service

import (
	baseStore "gitee.com/zaiqiang231/go-base-app/base_app/store"
	"gitee.com/zaiqiang231/zcamp-service-camp/app/model"
	"gitee.com/zaiqiang231/zcamp-service-camp/app/model/req"
	"gitee.com/zaiqiang231/zcamp-service-camp/app/util"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type ServiceProduct struct{}

var ServiceProductInstance = new(ServiceProduct)

func (receiver ServiceProduct) CreateProduct(ctx *gin.Context, request req.ProductCreateReq) (err error) {
	baseStore.GetDataStore().Execute(func(db *gorm.DB) {
		uniqueId, tmperr := util.GetProductId(ctx)
		if tmperr != nil {
			err = tmperr
			return
		}
		request.CommodityId = uniqueId
		err = db.Create(&request.Product).Error
	})
	return err
}

func (receiver ServiceProduct) ProductListForCamp(ctx *gin.Context, info req.ProductListForCampReq) (list interface{}, total int64, err error) {
	baseStore.GetDataStore().Execute(func(db *gorm.DB) {
		limit := info.PageSize
		offset := info.PageSize * (info.Page - 1)
		var tempDb = db.Where("camp_id = ?", info.CampID)
		var tmpList []model.Product
		err = tempDb.Model(&model.Product{}).Count(&total).Error
		if err != nil {
			return
		}
		err = tempDb.Model(&model.Product{}).Offset(offset).Limit(limit).Find(&tmpList).Error
		if err != nil {
			return
		}
		list = tmpList
	})
	return
}
